﻿using System.Collections.Generic;
using System.Threading;
using Csla.Core;
using Csla.Rules;

namespace Validation
{
    public class NumericLessThanValidation : ValidationBase
    {
        private IPropertyInfo CompareTo { get; set; }
        public bool IsEqual { get; set; }
        public NumericLessThanValidation(Csla.Core.IPropertyInfo primaryProperty, IPropertyInfo compareToProperty, string ValidationMessage, bool IsEqual)
            : base(primaryProperty, ValidationMessage)
        {
            CompareTo = compareToProperty;
            this.IsEqual = IsEqual;
            if (InputProperties == null)
            {
                InputProperties = new List<IPropertyInfo>();
            }
            InputProperties.Add(primaryProperty);
            InputProperties.Add(compareToProperty);
        }

        /// <summary>
        /// Does the check for primary propert less than compareTo property
        /// </summary>
        /// <param name="context">Rule context object.</param>
        protected override void Execute(RuleContext context)
        {
            var value1 = (dynamic)context.InputPropertyValues[PrimaryProperty];
            var value2 = (dynamic)context.InputPropertyValues[CompareTo];

            bool expressionCheck = IsEqual ? value1 > value2 : value1 >= value2;
            if (expressionCheck)
            {
                context.AddErrorResult(this.ValidationMessage);
                return;
            }
        }
    }
}
